
import json
import sys
import time

from analyze.analyzer import JsonAnalyzer
from download.sub.smt_downloader import smtDownloader
from handle.handler import BasicHandler

import logging
import traceback

from store.sub.smt import SmtProjectStore, SmtProjectDetailStore, SmtInfoBaseProjectDetailStore


# 机构募资事件详情
class SmtProjectHandler(BasicHandler):
    def __init__(self, config):
        super(SmtProjectHandler, self).__init__(config)
        self.mdb = config['mdb']

    def get_downloader(self):
        return smtDownloader(self.config)

    def get_analyzer(self):
        return JsonAnalyzer()

    def get_store(self):
        return SmtProjectDetailStore(self.config)

    def duplicated_key(self, task):
        return 'duplicated:{}:{}'.format(self.name, task['project_id'])

    def save(self, result, task):
        time.sleep(3)
        result = result.json()
        if result["success"]:
            try:
                result_data = json.loads("".join(json.dumps(result['result'])).replace(u'\xa0', u' '))
            except Exception as e:
                logging.error(e)
                logging.error("没有获取到相关信息")
                logging.error(traceback.format_exc())
            try:
                if result_data:
                    # for data in result_data:
                    result_data['qkid'] = task['project_id']
                    self.store.set(self.store.table, result_data)
                    self.mdb.commit()
                else:
                    logging.error("没有相关的基金信息" + task["project_id"])
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
        else:
            logging.info("请求数据不成功")
            logging.info(result["msg"])
            self.rds.rpush(self.queue_name, json.dumps(task))
            sys.exit()


# 机构募资事件列表
class SmtInfoListProjectHandler(BasicHandler):
    def __init__(self, config):
        super(SmtInfoListProjectHandler, self).__init__(config)
        self.mdb = config['mdb']

    def get_downloader(self):
        return smtDownloader(self.config)

    def get_analyzer(self):
        return JsonAnalyzer()

    def get_store(self):
        return SmtProjectStore(self.config)

    def duplicated_key(self, task):
        return 'duplicated:{}:{}'.format(self.name, task['project_id'])

    def save(self, result, task):
        time.sleep(3)
        result = result.json()
        if result["success"]:
            try:
                result_data = json.loads("".join(json.dumps(result['result'])).replace(u'\xa0', u' '))
            except Exception as e:
                logging.error(e)
                logging.error("没有获取到相关信息")
                logging.error(traceback.format_exc())
            try:
                if result_data:
                    # for data in result_data:
                    result_data['qkid'] = task['project_id']
                    self.store.set(self.store.table, result_data)
                    self.mdb.commit()
                else:
                    logging.error("没有相关的基金信息" + task["project_id"])
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
        else:
            logging.info("请求数据不成功")
            logging.info(result["msg"])
            self.rds.rpush(self.queue_name, json.dumps(task))
            sys.exit()


# 机构募资事件详情base
class SmtInfoBaseProjectHandler(BasicHandler):
    def __init__(self, config):
        super(SmtInfoBaseProjectHandler, self).__init__(config)
        self.mdb = config['mdb']

    def get_downloader(self):
        return smtDownloader(self.config)

    def get_analyzer(self):
        return JsonAnalyzer()

    def get_store(self):
        return SmtInfoBaseProjectDetailStore(self.config)

    def duplicated_key(self, task):
        return 'duplicated:{}:{}'.format(self.name, task['project_id'])

    def save(self, result, task):
        time.sleep(3)
        result = result.json()
        if result["success"]:
            try:
                result_data = json.loads("".join(json.dumps(result['result'])).replace(u'\xa0', u' '))
            except Exception as e:
                logging.error(e)
                logging.error("没有获取到相关信息")
                logging.error(traceback.format_exc())
            try:
                if result_data:
                    # for data in result_data:
                    result_data['qkid'] = task['project_id']
                    self.store.set(self.store.table, result_data)
                    self.mdb.commit()
                else:
                    logging.error("没有相关的基金信息" + task["project_id"])
            except Exception as e:
                logging.error(e)
                logging.error(traceback.format_exc())
        else:
            logging.info("请求数据不成功")
            logging.info(result["msg"])
            self.rds.rpush(self.queue_name, json.dumps(task))
            sys.exit()
